import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/widget/my_text.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/bloc/content_curator_cubit.dart';
import 'package:grint/bloc/auth_cubit.dart';
import 'package:grint/entity/content_submission.dart';
import 'package:grint/entity/user.dart';
import 'package:grint/utils/whisper.dart';
import 'package:grint/widget/auth_prompt_dialog.dart';

enum ContentUploadType { challengeShare, dailyShare }

class CreatePage extends StatefulWidget {
  final ContentUploadType uploadType;
  final String? preselectedChallenge;

  const CreatePage({
    super.key,
    this.uploadType = ContentUploadType.dailyShare,
    this.preselectedChallenge,
  });

  @override
  State<CreatePage> createState() => _CreatePageState();
}

class _CreatePageState extends State<CreatePage> {
  final TextEditingController _descriptionController = TextEditingController();
  List<AssetEntity> selectedAssets = [];
  List<String> selectedImagePaths = [];
  String? selectedVideoPath;
  String? selectedVideoThumbnail;
  String? selectedChallengeTask;

  final List<Map<String, String>> challengeTasks = [
    {'id': 'brush_teeth', 'title': 'Brush teeth', 'tag': '#Brush teeth'},
    {'id': 'dental_floss', 'title': 'Dental floss', 'tag': '#Dental floss'},
    {'id': 'daily_food', 'title': 'Daily food', 'tag': '#Daily food'},
  ];

  @override
  void initState() {
    super.initState();
    // 设置预选择的挑战任务
    if (widget.preselectedChallenge != null) {
      selectedChallengeTask = widget.preselectedChallenge;
    }
  }

  @override
  void dispose() {
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.lightBlue,
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/commonBg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              _constructHeaderSection(context),

              Expanded(
                child: SingleChildScrollView(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _assembleMediaUploadArea(),

                      SizedBox(height: 16.h),

                      _renderDescriptionSection(),

                      SizedBox(height: 16.h),

                      if (widget.uploadType == ContentUploadType.challengeShare)
                        _generateChallengeSelector(),

                      SizedBox(height: 16.h),

                      _createPublishButton(context),

                      SizedBox(height: 16.h),

                      GestureDetector(
                        onTap: () async {
                          await launchUrl(
                            Uri.parse(
                              'https://www.freeprivacypolicy.com/live/56bca466-eac6-41d2-8223-bb76973f5503',
                            ),
                            mode: LaunchMode.inAppBrowserView,
                          );
                        },
                        child: Center(
                          child: GestureDetector(
                            onTap: _navigateToEula,
                            child: MyText(
                              text: 'EULA',
                              type: TextType.miSans,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w400,
                              color: AppColors.black,
                              decoration: TextDecoration.underline,
                            ),
                          ),
                        ),
                      ),

                      SizedBox(height: 40.h),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _constructHeaderSection(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 12.h),
      child: Row(
        children: [
          BlackButton(
            icon: IconFontIcons.iconArrowLeft,
            onTap: () => context.pop(),
          ),
          Expanded(
            child: Center(
              child: MyText(
                text: 'Editor',
                type: TextType.rubik,
                fontSize: 28.sp,
                color: AppColors.black,
                fontWeight: FontWeight.w900,
              ),
            ),
          ),
          SizedBox(width: 26.w),
        ],
      ),
    );
  }

  Widget _assembleMediaUploadArea() {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20.r),
      ),
      padding: EdgeInsets.all(16.w),
      child: Column(
        children: [
          // 主要上传区域
          Container(
            width: double.infinity,
            height: 136.h,
            decoration: BoxDecoration(
              color: Color(0xFFF5F5F5),
              borderRadius: BorderRadius.circular(16.r),
              border: Border.all(color: Color(0xFFE0E0E0), width: 1.w),
            ),
            child:
                selectedVideoPath != null || selectedImagePaths.isNotEmpty
                    ? _displaySelectedMedia()
                    : _renderUploadPlaceholder(),
          ),

          SizedBox(height: 16.h),

          // 缩略图区域（仅图片时显示）
          (selectedImagePaths.isNotEmpty && selectedVideoPath == null)
              ? _constructThumbnailRow()
              : SizedBox(height: 95.h),
        ],
      ),
    );
  }

  Widget _displaySelectedMedia() {
    if (selectedVideoPath != null) {
      return Stack(
        children: [
          Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(16.r),
              child:
                  selectedVideoThumbnail != null
                      ? Stack(
                        children: [
                          // 显示缩略图
                          Image.file(
                            File(selectedVideoThumbnail!),
                            width: double.infinity,
                            height: double.infinity,
                            fit: BoxFit.cover,
                            errorBuilder: (context, error, stackTrace) {
                              return _buildVideoPlaceholder();
                            },
                          ),
                          // 播放按钮覆盖层
                          Center(
                            child: Container(
                              width: 60.w,
                              height: 60.w,
                              decoration: BoxDecoration(
                                color: Colors.black.withValues(alpha: 0.6),
                                shape: BoxShape.circle,
                              ),
                              child: Icon(
                                Icons.play_arrow,
                                size: 32.sp,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ],
                      )
                      : _buildVideoPlaceholder(),
            ),
          ),

          // 删除按钮
          Positioned(
            top: 8.w,
            right: 8.w,
            child: GestureDetector(
              onTap: _removeVideo,
              child: Container(
                width: 24.w,
                height: 24.w,
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.6),
                  shape: BoxShape.circle,
                ),
                child: Icon(Icons.close, color: Colors.white, size: 16.sp),
              ),
            ),
          ),
        ],
      );
    }

    if (selectedImagePaths.isNotEmpty && selectedAssets.isNotEmpty) {
      return Stack(
        children: [
          Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(16.r),
              child: AssetEntityImage(
                selectedAssets.first,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.black12,
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            Icons.image_outlined,
                            size: 48.sp,
                            color: AppColors.textGrey,
                          ),
                          SizedBox(height: 8.h),
                          MyText(
                            text:
                                '${selectedImagePaths.length} Image${selectedImagePaths.length > 1 ? 's' : ''} Selected',
                            type: TextType.miSans,
                            fontSize: 14.sp,
                            color: AppColors.textGrey,
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
          ),

          // 图片数量标识（如果有多张图片）
          if (selectedImagePaths.length > 1)
            Positioned(
              top: 8.w,
              left: 8.w,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.6),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: MyText(
                  text: '${selectedImagePaths.length} Images',
                  type: TextType.miSans,
                  fontSize: 12.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),

          // 删除按钮
          Positioned(
            top: 8.w,
            right: 8.w,
            child: GestureDetector(
              onTap: _removeAllImages,
              child: Container(
                width: 24.w,
                height: 24.w,
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.6),
                  shape: BoxShape.circle,
                ),
                child: Icon(Icons.close, color: Colors.white, size: 16.sp),
              ),
            ),
          ),
        ],
      );
    }

    return SizedBox.shrink();
  }

  Widget _renderUploadPlaceholder() {
    return GestureDetector(
      onTap: _handleMediaSelection,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(IconFontIcons.iconPhoto, size: 32.sp, color: AppColors.textGrey),
          SizedBox(height: 12.h),
          MyText(
            text: 'Upload A Video Or Picture',
            type: TextType.miSans,
            fontSize: 12.sp,
            color: AppColors.textGrey,
            fontWeight: FontWeight.w500,
          ),
        ],
      ),
    );
  }

  Widget _constructThumbnailRow() {
    return Row(
      children: [
        ...selectedAssets.asMap().entries.map((entry) {
          final int index = entry.key;
          final AssetEntity asset = entry.value;

          return Container(
            width: 74.w,
            height: 95.w,
            margin: EdgeInsets.only(right: 8.w),
            child: Stack(
              children: [
                // 图片缩略图
                Container(
                  width: 74.w,
                  height: 95.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.r),
                    color: Color(0xFFE0E0E0),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8.r),
                    child: AssetEntityImage(
                      asset,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          color: Color(0xFFE0E0E0),
                          child: Icon(
                            Icons.image,
                            color: AppColors.textGrey,
                            size: 24.sp,
                          ),
                        );
                      },
                    ),
                  ),
                ),

                // 删除按钮
                Positioned(
                  top: 4.w,
                  right: 4.w,
                  child: GestureDetector(
                    onTap: () => _removeImageAtIndex(index),
                    child: Container(
                      width: 20.w,
                      height: 20.w,
                      decoration: BoxDecoration(
                        color: Colors.black.withValues(alpha: 0.6),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.close,
                        color: Colors.white,
                        size: 14.sp,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          );
        }),

        if (selectedImagePaths.length < 3)
          GestureDetector(
            onTap: _handleAddMoreImages,
            child: Container(
              width: 74.w,
              height: 95.w,
              decoration: BoxDecoration(
                color: Color(0xFFF0F0F0),
                borderRadius: BorderRadius.circular(8.r),
                border: Border.all(color: Color(0xFFE0E0E0), width: 1.w),
              ),
              child: Icon(Icons.add, color: AppColors.textGrey, size: 24.sp),
            ),
          ),
      ],
    );
  }

  Widget _renderDescriptionSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        MyText(
          text: 'Content description',
          type: TextType.miSans,
          fontSize: 18.sp,
          fontWeight: FontWeight.w600,
          color: AppColors.black,
        ),
        SizedBox(height: 12.h),
        Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16.r),
          ),
          child: TextField(
            controller: _descriptionController,
            maxLines: 5,
            decoration: InputDecoration(
              hintText: 'Add the main text',
              hintStyle: TextStyle(
                color: AppColors.textGrey,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
              ),
              border: InputBorder.none,
              contentPadding: EdgeInsets.all(16.w),
            ),
            style: TextStyle(
              color: AppColors.black,
              fontSize: 14.sp,
              fontWeight: FontWeight.w400,
            ),
          ),
        ),
      ],
    );
  }

  Widget _generateChallengeSelector() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        MyText(
          text: 'Challenge',
          type: TextType.miSans,
          fontSize: 18.sp,
          fontWeight: FontWeight.w600,
          color: AppColors.black,
        ),
        SizedBox(height: 12.h),
        SizedBox(
          height: 40.h,
          child: ListView.separated(
            scrollDirection: Axis.horizontal,
            itemCount: challengeTasks.length,
            separatorBuilder: (context, index) => SizedBox(width: 8.w),
            itemBuilder: (context, index) {
              final task = challengeTasks[index];
              final isSelected = selectedChallengeTask == task['id'];

              return GestureDetector(
                onTap: () => _handleChallengeSelection(task['id']!),
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 8.h,
                  ),
                  decoration: BoxDecoration(
                    color: isSelected ? AppColors.tabBlue : Colors.white,
                    borderRadius: BorderRadius.circular(20.r),
                    border: Border.all(
                      color: isSelected ? AppColors.tabBlue : Color(0xFFE0E0E0),
                      width: 1.w,
                    ),
                  ),
                  child: Center(
                    child: MyText(
                      text: task['tag']!,
                      type: TextType.miSans,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w600,
                      color: isSelected ? AppColors.black : AppColors.textGrey,
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _createPublishButton(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 50.h,
      decoration: BoxDecoration(
        color: AppColors.black,
        borderRadius: BorderRadius.circular(25.r),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => _executePublishAction(context),
          borderRadius: BorderRadius.circular(25.r),
          child: Center(
            child: MyText(
              text: 'Publish',
              type: TextType.miSans,
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }

  // 事件处理方法
  void _handleMediaSelection() {
    _showMediaSelectionDialog();
  }

  void _handleAddMoreImages() {
    if (selectedImagePaths.length < 3) {
      _selectImages();
    }
  }

  /// 删除指定索引的图片
  void _removeImageAtIndex(int index) {
    setState(() {
      if (index < selectedAssets.length) {
        selectedAssets.removeAt(index);
      }
      if (index < selectedImagePaths.length) {
        selectedImagePaths.removeAt(index);
      }
    });

    Whisper.murmur('Image removed');
  }

  /// 删除选择的视频
  void _removeVideo() {
    setState(() {
      selectedVideoPath = null;
      selectedVideoThumbnail = null;
    });

    Whisper.murmur('Video removed');
  }

  /// 删除所有选择的图片
  void _removeAllImages() {
    setState(() {
      selectedAssets.clear();
      selectedImagePaths.clear();
    });

    Whisper.murmur('All images removed');
  }

  /// 显示媒体选择对话框
  void _showMediaSelectionDialog() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder:
          (context) => Container(
            padding: EdgeInsets.all(20.w),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                MyText(
                  text: 'Select Media Type',
                  type: TextType.miSans,
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w600,
                  color: AppColors.black,
                ),
                SizedBox(height: 20.h),

                Row(
                  children: [
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                          _selectImages();
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 16.h),
                          decoration: BoxDecoration(
                            color: AppColors.lightBlue,
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          child: Column(
                            children: [
                              Icon(
                                Icons.image,
                                size: 32.sp,
                                color: AppColors.blue,
                              ),
                              SizedBox(height: 8.h),
                              MyText(
                                text: 'Images (1-3)',
                                type: TextType.miSans,
                                fontSize: 14.sp,
                                color: AppColors.black,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),

                    SizedBox(width: 16.w),

                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                          _selectVideo();
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 16.h),
                          decoration: BoxDecoration(
                            color: AppColors.lightBlue,
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          child: Column(
                            children: [
                              Icon(
                                Icons.videocam,
                                size: 32.sp,
                                color: AppColors.blue,
                              ),
                              SizedBox(height: 8.h),
                              MyText(
                                text: 'Video',
                                type: TextType.miSans,
                                fontSize: 14.sp,
                                color: AppColors.black,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),

                SizedBox(height: 20.h),
              ],
            ),
          ),
    );
  }

  /// 选择图片
  Future<void> _selectImages() async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 3,
          requestType: RequestType.image,
          selectedAssets: selectedAssets,
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        // 清除视频选择
        selectedVideoPath = null;

        // 获取图片文件路径
        final List<String> imagePaths = [];
        for (final asset in assets) {
          final file = await asset.file;
          if (file != null) {
            imagePaths.add(file.path);
          }
        }

        setState(() {
          selectedAssets = assets;
          selectedImagePaths = imagePaths;
        });

        Whisper.murmur(
          '${assets.length} image${assets.length > 1 ? 's' : ''} selected',
        );
      } else {}
    } catch (e) {
      Whisper.hiss('Failed to select images: ${e.toString()}');
    }
  }

  Future<void> _selectVideo() async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.video,
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        Whisper.chant(message: 'Processing video...');

        final file = await assets.first.file;
        if (file != null) {
          selectedAssets.clear();
          selectedImagePaths.clear();

          await _processSelectedVideo(file, assets.first);

          Whisper.silence();
          Whisper.murmur('Video selected');
        } else {
          Whisper.silence();
          Whisper.hiss('Failed to get video file');
        }
      }
    } catch (e) {
      Whisper.silence();
      Whisper.hiss('Failed to select video: ${e.toString()}');
    }
  }

  Future<void> _processSelectedVideo(File videoFile, AssetEntity asset) async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final videoDir = Directory('${directory.path}/videos');

      if (!await videoDir.exists()) {
        await videoDir.create(recursive: true);
      }

      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final extension = videoFile.path.split('.').last;
      final localVideoPath = '${videoDir.path}/video_$timestamp.$extension';

      final localVideoFile = await videoFile.copy(localVideoPath);

      final thumbnailPath = await _generateVideoThumbnail(asset);

      setState(() {
        selectedVideoPath = localVideoFile.path;
        selectedVideoThumbnail = thumbnailPath;
      });
    } catch (e) {
      throw Exception('Failed to process video: $e');
    }
  }

  Future<String?> _generateVideoThumbnail(AssetEntity asset) async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final thumbnailDir = Directory('${directory.path}/thumbnails');

      if (!await thumbnailDir.exists()) {
        await thumbnailDir.create(recursive: true);
      }

      final thumbnailData = await asset.thumbnailDataWithSize(
        const ThumbnailSize(200, 200),
        quality: 80,
      );

      if (thumbnailData != null) {
        final timestamp = DateTime.now().millisecondsSinceEpoch;
        final thumbnailPath = '${thumbnailDir.path}/thumb_$timestamp.jpg';

        final thumbnailFile = File(thumbnailPath);
        await thumbnailFile.writeAsBytes(thumbnailData);

        return thumbnailPath;
      }

      return null;
    } catch (e) {
      print('Failed to generate thumbnail: $e');
      return null;
    }
  }

  void _handleChallengeSelection(String taskId) {
    setState(() {
      selectedChallengeTask = selectedChallengeTask == taskId ? null : taskId;
    });
  }

  void _executePublishAction(BuildContext context) {
    final cubit = context.read<ContentCuratorCubit>();
    final authState = context.read<AuthCubit>().state;

    if (authState.currentUser == null) {
      // 显示弹窗并处理跳转
      _showAuthPromptAndNavigate(context);
      return;
    }

    if (_descriptionController.text.trim().isEmpty) {
      Whisper.hiss('Please enter description');
      return;
    }

    if (selectedImagePaths.isEmpty && selectedVideoPath == null) {
      Whisper.hiss('Please select media');
      return;
    }

    if (widget.uploadType == ContentUploadType.challengeShare &&
        selectedChallengeTask == null) {
      Whisper.hiss('Please select a challenge task');
      return;
    }

    _publishContent(cubit, authState.currentUser!);
  }

  Future<void> _publishContent(
    ContentCuratorCubit cubit,
    User currentUser,
  ) async {
    Whisper.chant(message: 'Publishing content...');

    await Future.delayed(const Duration(seconds: 2));

    Whisper.silence();

    try {
      bool success = false;

      if (selectedVideoPath != null) {
        // 发布视频内容
        success = await cubit.publishVideoSubmission(
          author: currentUser,
          category:
              widget.uploadType == ContentUploadType.challengeShare
                  ? SubmissionCategory.challengeShare
                  : SubmissionCategory.dailyShare,
          description: _descriptionController.text.trim(),
          videoPath: selectedVideoPath!,
          thumbnailPath: selectedVideoThumbnail,
          challengeTaskId: selectedChallengeTask,
        );
      } else if (selectedImagePaths.isNotEmpty) {
        // 发布图片内容
        success = await cubit.publishImageSubmission(
          author: currentUser,
          category:
              widget.uploadType == ContentUploadType.challengeShare
                  ? SubmissionCategory.challengeShare
                  : SubmissionCategory.dailyShare,
          description: _descriptionController.text.trim(),
          imagePaths: selectedImagePaths,
          challengeTaskId: selectedChallengeTask,
        );
      }

      Whisper.silence();

      if (success) {
        if (mounted) {
          // 发布成功，返回上一页
          context.pop();
        }
      } else {
        Whisper.hiss('Failed to publish content');
      }
    } catch (e) {
      Whisper.silence();
      Whisper.shriek('Failed to publish: ${e.toString()}');
    }
  }

  void _navigateToEula() async {
    await launchUrl(
      Uri.parse(
        'https://www.freeprivacypolicy.com/live/56bca466-eac6-41d2-8223-bb76973f5503',
      ),
      mode: LaunchMode.inAppBrowserView,
    );
  }

  /// 构建视频占位符
  Widget _buildVideoPlaceholder() {
    return Container(
      color: Colors.black12,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.play_circle_outline,
              size: 48.sp,
              color: AppColors.textGrey,
            ),
            SizedBox(height: 8.h),
            MyText(
              text: 'Video Selected',
              type: TextType.miSans,
              fontSize: 14.sp,
              color: AppColors.textGrey,
            ),
          ],
        ),
      ),
    );
  }

  /// 显示登录提示弹窗并处理跳转
  void _showAuthPromptAndNavigate(BuildContext context) {
    AuthPromptHelper.showAuthPrompt(
      context: context,
      title: 'Login Required',
      message:
          'You need to log in to publish content. Please log in to continue.',
      actionText: 'Go to Login',
      onAction: () {
        // 现在使用原生弹窗，可以正常使用 push
        context.push('/auth');
      },
    );
  }
}
